<template>
    <statusBar></statusBar>
    <view class="header" @click="chooseHeader">
        <view class="imgBox">
            <image v-if="infomation.avatar" :src="infomation.avatar" mode="aspectFill"></image>
            <image v-else class="camera" src="/static/common/icon_camera.png"></image>
        </view>

        <view class="text">{{ infomation.avatar ? '' : '上传你的头像' }}</view>
    </view>

    <view class="content">
        <view class="inputs">
            <view class="item">
                <view class="itemTitle">你的昵称</view>
                <view class="inputBox">
                    <input type="text" :maxlength="5" v-model.trim="infomation.nickName" placeholder="五个字以内" />
                </view>
            </view>

            <view class="item">
                <view class="itemTitle">所在地区</view>
                <view class="inputBox" @click="openAreaSelect">
                    <view class="text">
                        <span v-for="(item, index) in areaSelectList" :key="index">
                            {{ item.areaName === '请选择' ? '' : item.areaName }}{{ index !== areaSelectList.length - 1 ? '/' : '' }}
                        </span>

                        <!--  {{ infomation.province + infomation.city + infomation.district + infomation.street }} -->
                    </view>
                    <image class="more" src="/static/common/icon_more.png"></image>
                </view>
            </view>

            <view class="item" v-if="infomation2.identityType != '0'">
                <view class="itemTitle">小区名称</view>
                <view class="inputBox">
                    <input v-model.trim="infomation.community" placeholder="请输入小区名称" />

                    <view class="listBox" v-if="suggestions.length != 0">
                        <scroll-view scroll-y="true" style="height: 400rpx">
                            <view class="suggestionsItem" @click="chooseCommunity(item)" v-for="item in suggestions" :key="item.title">
                                {{ item.title }}
                            </view>
                        </scroll-view>
                    </view>
                </view>
            </view>

            <view class="item">
                <view class="itemTitle">详细地址</view>
                <view class="inputBox">
                    <input v-model.trim="infomation.address" placeholder="请输入详细地址" />
                </view>
            </view>
        </view>

        <view class="submit" @click="SubmitEvent">进入</view>
    </view>

    <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
        <view class="popupContent">
            <view class="popupTop">
                <view class="title">
                    <view v-for="(item, index) in areaSelectList" :class="areaCurrentIndex == index && 'active'" @click="chooseItem(index)">{{ item?.areaName }}</view>
                </view>
                <image src="/static/common/icon_close.png" class="close" @click="closePopup"></image>
            </view>

            <view class="scrollViewBox">
                <view class="title">请选择</view>

                <scroll-view scroll-y="true" class="scrollView">
                    <view class="scrollContent">
                        <view
                            class="item"
                            :class="item?.areaNo === areaSelectList[areaCurrentIndex]?.areaNo && 'active'"
                            v-for="(item, index) in allAreaList"
                            :key="index"
                            @click="selectArea(index)"
                        >
                            {{ item?.areaName }}
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { nextTick, reactive, ref, toRaw, watch } from 'vue';
import { uploadFile } from '@/utils/request';
import { commonApis, userApis } from '@/utils/apis.ts';
import { checkStrLengthIsNotZero, encryption, debounceImmediate } from '@/utils/utils';
import env from '@/config/env';
let infomation = reactive({
    avatar: '',
    nickName: '',
    province: '',
    city: '',
    district: '',
    street: '',
    streetId: '',
    community: '',
    address: '',
    latitude: null,
    longitude: null
});

const infomation2 = ref({});

onLoad((e) => {
    let res = JSON.parse(e.infomation);
    infomation2.value = res;
});

let areaCurrentIndex = ref(0);
let allAreaList = ref([]);
let areaSelectList = reactive([]);

const chooseItem = async (index) => {
    areaCurrentIndex.value = index;
    let res = await commonApis.getArea({
        parentAreaNo: index === 0 ? '' : areaSelectList[index - 1].areaNo,
        parentLevel: index === 0 ? '' : areaSelectList[index - 1].areaLevel
    });
    allAreaList.value = res.data;
};

const selectArea = async (index) => {
    if (areaSelectList.length > areaCurrentIndex.value) {
        areaSelectList.length = areaCurrentIndex.value + 1;
    }
    let selectItem = allAreaList.value[index];
    areaSelectList[areaCurrentIndex.value] = selectItem;

    switch (areaCurrentIndex.value) {
        case 0:
            infomation.province = selectItem.areaName;
            break;
        case 1:
            infomation.city = selectItem.areaName;
            break;
        case 2:
            infomation.district = selectItem.areaName;
            break;
        case 3:
            infomation.street = selectItem.areaName;
            infomation.streetId = selectItem.areaNo;
            closePopup();
            break;
        default:
            break;
    }

    if (areaCurrentIndex.value < 3) {
        areaCurrentIndex.value++;

        areaSelectList[areaCurrentIndex.value] = {
            areaName: '请选择'
        };
        let res = await commonApis.getArea({
            parentAreaNo: selectItem.areaNo,
            parentLevel: selectItem.areaLevel
        });
        allAreaList.value = res.data;
    }
};

// 弹出地区选择
const popup = ref();
const openAreaSelect = () => {
    nextTick(async () => {
        popup.value.open();
        areaCurrentIndex.value = 0;
        if (areaSelectList.length == 0) {
            areaSelectList.push({
                areaName: '请选择'
            });
        }

        let res = await commonApis.getArea({});
        allAreaList.value = res.data;
    });
};
const closePopup = () => {
    nextTick(() => {
        popup.value.close();
    });
};

const searchFlage = ref(false);
watch(
    () => infomation.community,
    (newVal, oldVal) => {
        if (searchFlage.value) {
            searchFlage.value = false;
            return;
        }
        getSuggestions(newVal);
    }
);

const communityId = ref(null);
const chooseCommunity = (item) => {
    communityId.value = item.id;
    infomation.community = item.title;
    infomation.latitude = item.location.lat;
    infomation.longitude = item.location.lng;
    searchFlage.value = true;
    suggestions.value = [];
};

const suggestions = ref([]);
const getSuggestions = debounceImmediate(async (keyword) => {
    const key = 'TYKBZ-75VKQ-HT457-2XZYT-FYTQT-RAFI5'; // 替换为你的腾讯地图API Key
    const url = `https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=${encodeURIComponent(infomation.street + keyword)}&key=${key}`;
    uni.request({
        url: url,
        method: 'GET',
        success: (res) => {
            // 调试信息
            if (res.statusCode === 200) {
                const data = res.data;
                if (data.status === 0 && data.data.length > 0) {
                    suggestions.value = data.data.map((item) => ({
                        title: item.title,
                        id: item.id,
                        location: item.location
                    }));
                } else {
                    suggestions.value = [];
                    console.log('未找到相关结果');
                    uni.showToast({
                        title: '未找到相关结果',
                        icon: 'none'
                    });
                }
            } else {
                console.error('请求失败：', res);
                uni.showToast({
                    title: '请求失败',
                    icon: 'none'
                });
            }
        },
        fail: (err) => {
            console.error('请求失败：', err);
            uni.showToast({
                title: '请求失败',
                icon: 'none'
            });
        }
    });
});

const SubmitEvent = async () => {
    if (!checkStrLengthIsNotZero(infomation.avatar)) {
        uni.showToast({
            icon: 'none',
            title: '请上传你的头像'
        });
        return;
    }
    if (areaSelectList.length === 0 || areaSelectList[0].areaName == '请选择') {
        uni.showToast({
            icon: 'none',
            title: '请选择所在地区'
        });
        return;
    }

    if (!checkStrLengthIsNotZero(infomation.nickName)) {
        uni.showToast({
            icon: 'none',
            title: '请填写用户昵称'
        });
        return;
    }
    if (infomation2.value.identityType !== '0' && !checkStrLengthIsNotZero(infomation.community)) {
        uni.showToast({
            icon: 'none',
            title: '请填写小区名称'
        });
        return;
    }
    if (!checkStrLengthIsNotZero(infomation.address)) {
        uni.showToast({
            icon: 'none',
            title: '请填写详细地址'
        });
        return;
    }

    uni.showLoading({
        title: '提交中',
        mask: true
    });

    infomation.avatar = await uploadFile(infomation.avatar);

    let p: any = { ...infomation, ...infomation2.value };

    if (communityId.value) {
        p = { ...p, communityId: communityId.value };
    }

    console.log(communityId.value, p);
    await userApis.register(p);
    await loginMethods();
    uni.setStorageSync('userRole', infomation2.value.identityType);
    uni.setStorageSync('isRegisterFlag', true);

    uni.switchTab({
        url: '/pages/home/home'
    });
};

const loginMethods = async () => {
    const res = await userApis.getValidateCode({
        randomStr: Date.now()
    });

    const userInfo = {
        username: infomation2.value.phone,
        password: infomation2.value.password,
        code: res.data.code,
        grant_type: 'password',
        scope: 'server',
        randomStr: res.data.randomStr
    };
    const user = encryption({
        data: userInfo,
        key: env.securityKey,
        param: ['password']
    });

    await userApis.loginByPassword(user).then((res) => {
        let result = res;
        result.expires_in = new Date().getTime() + result.expires_in * 1000;
        uni.setStorageSync('userLoginInfo', JSON.stringify(result));
        uni.setStorageSync('userId', res.user_id);
    });
};

// 选择照片
const chooseHeader = () => {
    uni.chooseImage({
        count: 1, //默认9
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success(res) {
            infomation.avatar = res.tempFilePaths[0];
        }
    });
};
</script>

<style lang="scss" scoped>
.content {
    padding: 0 84rpx;
    .inputs {
        width: 100%;
        .item {
            width: 100%;
            padding: 24rpx 0;
            margin-bottom: 16rpx;
            display: flex;
            align-items: center;
            border-bottom: 2rpx solid #f2f2f2;

            .itemTitle {
                width: 130rpx;
                font-size: 28rpx;
                line-height: 1;
                color: #393939;
                border-right: 2rpx solid #ccc;
            }
            .inputBox {
                flex: 1;
                padding-left: 12rpx;
                display: flex;
                align-items: center;
                position: relative;

                .text {
                    flex: 1;
                    font-size: 24rpx;
                    color: #333333;
                    line-height: 1.5;
                }
                .more {
                    margin-left: 20rpx;
                    width: 24rpx;
                    height: 24rpx;
                }

                input {
                    flex: 1;
                    height: 40rpx;
                    font-size: 24rpx;
                    color: #393939;
                    line-height: 40rpx;

                    &::placeholder {
                        color: #999999;
                    }
                }

                .listBox {
                    position: absolute;
                    z-index: 5;
                    width: 100%;
                    top: 100%;
                    left: 0;
                    background-color: #fff;
                    padding: 20rpx 30rpx;
                    box-shadow: 0 0 5rpx 5rpx rgba(0, 0, 0, 0.08);

                    .suggestionsItem {
                        height: 60rpx;
                        border-bottom: 2rpx solid #ccc;
                        font-size: 24rpx;
                        line-height: 60rpx;
                        color: #393939;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;

                        &:last-child {
                            border-bottom: none;
                        }
                    }
                }
            }
        }
    }

    .forgetPassword {
        font-size: 28rpx;
        line-height: 1;
        height: 28rpx;
        color: #393939;
        text-align: right;
    }
}

.header {
    padding-top: 140rpx;
    padding-bottom: 80rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .imgBox {
        border-radius: 50%;
        background-color: #ccc;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 174rpx;
        height: 174rpx;
        overflow: hidden;
        position: relative;

        image {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 95%;
            height: 95%;
            border-radius: 50%;
        }

        .camera {
            width: 60rpx;
            height: 60rpx;
        }
    }

    .text {
        margin-top: 20rpx;
        font-size: 32rpx;
        line-height: 32rpx;
        height: 32rpx;
        color: #333333;
    }
}

.submit {
    margin: 40rpx auto 0;
    width: 572rpx;
    height: 78rpx;
    background: #2c72ff;
    border-radius: 54rpx;
    font-size: 28rpx;
    color: #ffffff;
    line-height: 78rpx;
    text-align: center;
}

.popupContent {
    width: 100%;
    background: #ffffff;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    padding: 46rpx 24rpx calc(env(safe-area-inset-bottom) + 20rpx);

    .popupTop {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
            font-size: 32rpx;
            color: #333333;
            display: flex;
            align-items: center;
            gap: 10rpx;
            view {
                border-radius: 8rpx;
                display: block;
                padding: 0 10rpx;
                max-width: 160rpx;
                height: 48rpx;
                font-size: 26rpx;
                color: #333333;
                line-height: 48rpx;
                text-align: center;
                background: #f2f3f5;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;

                &.active {
                    background: #2c72ff;
                    color: #fff;
                }
            }
        }
        .close {
            width: 40rpx;
            height: 40rpx;
        }
    }

    .scrollViewBox {
        padding: 20rpx 0 0;
        .title {
            font-size: 32rpx;
            color: #333333;
            margin-bottom: 30rpx;
        }

        .scrollView {
            height: 40vh;
            width: 100%;

            .scrollContent {
                .item {
                    font-size: 32rpx;
                    color: #333333;
                    padding: 18rpx 24rpx;
                    border-radius: 24rpx;
                    &:last-child {
                        margin: 0;
                    }

                    &.active {
                        color: #2c72ff;
                        background: #f2f2f2;
                    }
                }
            }
        }
    }
}
</style>
